-- This file is part of the Fantasy Grounds Open Foundation Ruleset project. 
-- For the latest information, see http://www.fantasygrounds.com/
--
-- Copyright 2008 SmiteWorks Ltd.
--
-- This file is provided under the Open Game License version 1.0a
-- Refer to the license.html file for the full license text
--
-- All producers of work derived from this material are advised to
-- familiarize themselves with the license, and to take special
-- care in providing the definition of Product Identity (as specified
-- by the OGL) in their products.
--
-- All material submitted to the Open Foundation Ruleset project must
-- contain this notice in a manner applicable to the source file type.


function updateVisibility()
	if sourceentry and window.adjustment.getValue() ~= 0 then
		setVisible(true);
	else
		setVisible(false);
	end
end

function getSource()
	return sourceentry;
end

function deleteSource()
	if sourceentry then
		local namenode = sourceentry.getChild("name", "string");
		if namenode then
			namenode.onUpdate = function() end;
		end
		sourceentry.onDelete = function() end;
	end

	sourceentry = nil;
	setValue(nil);
	
	if window.getDatabaseNode().getChild("source") then
		window.getDatabaseNode().getChild("source").delete();
	end
	
	updateVisibility();
end

function setSource(entry)
	deleteSource();

	sourceentry = entry;
	
	if sourceentry then
		window.getDatabaseNode().createChild("source", "string").setValue(sourceentry.getNodeName());
	
		sourceentry.createChild("name", "string").onUpdate = onSourceNameChange;
		sourceentry.onDelete = onSourceDelete;
	
		setValue("Update on: " .. sourceentry.createChild("name", "string").getValue());
		updateVisibility();
	end
end

function onSourceNameChange(source)
	setValue("Update on: " .. sourceentry.createChild("name", "string").getValue());
end

function onSourceDelete(source)
	if source == sourceentry then
		deleteSource();
	end
end

function onClickDown(button, x, y)
	if button == 2 then
		deleteSource();
	end
end

function onDrop(x, y, draginfo)
	if draginfo.isType("combattrackerentry") then
		setSource(draginfo.getCustomData());
		return true;
	end
end

function onInit()
	if window.getDatabaseNode() then
		local sourcenode = window.getDatabaseNode().getChild("source");
		if sourcenode and sourcenode.getValue() ~= "" then
			setSource(DB.findNode(sourcenode.getValue()));
		end
	end
end
